using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Users;

namespace UserManagementService.Users
{
    /// <summary>
    /// Matrix Framework 扩展用户实体
    /// 扩展ABP Identity的用户模型，添加业务特定属性
    /// </summary>
    public class User : FullAuditedAggregateRoot<Guid>, IMultiTenant
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public virtual Guid? TenantId { get; set; }

        /// <summary>
        /// 用户名
        /// </summary>
        public virtual string UserName { get; protected set; }

        /// <summary>
        /// 邮箱地址
        /// </summary>
        public virtual string Email { get; protected set; }

        /// <summary>
        /// 邮箱是否已确认
        /// </summary>
        public virtual bool EmailConfirmed { get; protected set; }

        /// <summary>
        /// 手机号码
        /// </summary>
        public virtual string? PhoneNumber { get; protected set; }

        /// <summary>
        /// 手机号码是否已确认
        /// </summary>
        public virtual bool PhoneNumberConfirmed { get; protected set; }

        /// <summary>
        /// 密码哈希
        /// </summary>
        public virtual string PasswordHash { get; protected set; }

        /// <summary>
        /// 安全码（用于密码重置等功能）
        /// </summary>
        public virtual string? SecurityStamp { get; protected set; }

        /// <summary>
        /// 两步验证密钥
        /// </summary>
        public virtual string? TwoFactorEnabled { get; protected set; }

        /// <summary>
        /// 锁定结束时间
        /// </summary>
        public virtual DateTime? LockoutEnd { get; protected set; }

        /// <summary>
        /// 是否允许登录锁定
        /// </summary>
        public virtual bool LockoutEnabled { get; protected set; }

        /// <summary>
        /// 登录失败次数
        /// </summary>
        public virtual int AccessFailedCount { get; protected set; }

        /// <summary>
        /// 用户是否激活
        /// </summary>
        public virtual bool IsActive { get; protected set; }

        /// <summary>
        /// 名字
        /// </summary>
        public virtual string? Name { get; protected set; }

        /// <summary>
        /// 姓氏
        /// </summary>
        public virtual string? Surname { get; protected set; }

        /// <summary>
        /// 显示名称（名字+姓氏）
        /// </summary>
        public virtual string? DisplayName { get; protected set; }

        /// <summary>
        /// 头像URL
        /// </summary>
        public virtual string? AvatarUrl { get; protected set; }

        /// <summary>
        /// 个人简介
        /// </summary>
        public virtual string? Bio { get; protected set; }

        /// <summary>
        /// 用户类型（0:普通用户 1:管理员 2:超级管理员）
        /// </summary>
        public virtual int UserType { get; protected set; }

        /// <summary>
        /// 用户状态（0:待激活 1:正常 2:禁用 3:已删除）
        /// </summary>
        public virtual UserStatus Status { get; protected set; }

        /// <summary>
        /// 最后登录时间
        /// </summary>
        public virtual DateTime? LastLoginTime { get; protected set; }

        /// <summary>
        /// 最后登录IP
        /// </summary>
        public virtual string? LastLoginIp { get; protected set; }

        /// <summary>
        /// 密码最后修改时间
        /// </summary>
        public virtual DateTime? PasswordChangedAt { get; protected set; }

        /// <summary>
        /// 用户角色关联
        /// </summary>
        public virtual ICollection<UserRole> UserRoles { get; protected set; }

        /// <summary>
        /// 用户组织关联
        /// </summary>
        public virtual ICollection<UserOrganizationUnit> OrganizationUnits { get; protected set; }

        /// <summary>
        /// 用户登录历史
        /// </summary>
        public virtual ICollection<UserLoginHistory> LoginHistories { get; protected set; }

        /// <summary>
        /// 用户活动日志
        /// </summary>
        public virtual ICollection<UserActivityLog> ActivityLogs { get; protected set; }

        protected User()
        {
            UserRoles = new Collection<UserRole>();
            OrganizationUnits = new Collection<UserOrganizationUnit>();
            LoginHistories = new Collection<UserLoginHistory>();
            ActivityLogs = new Collection<UserActivityLog>();
        }

        /// <summary>
        /// 创建新用户
        /// </summary>
        public User(
            Guid id,
            string userName,
            string email,
            string? name = null,
            string? surname = null,
            Guid? tenantId = null) : base(id)
        {
            SetUserName(userName);
            SetEmail(email);
            SetName(name);
            SetSurname(surname);
            TenantId = tenantId;

            // 默认值
            EmailConfirmed = false;
            PhoneNumberConfirmed = false;
            LockoutEnabled = true;
            IsActive = true;
            UserType = 0; // 普通用户
            Status = UserStatus.Pending; // 待激活
            AccessFailedCount = 0;

            // 生成安全码
            SecurityStamp = Guid.NewGuid().ToString();

            UserRoles = new Collection<UserRole>();
            OrganizationUnits = new Collection<UserOrganizationUnit>();
            LoginHistories = new Collection<UserLoginHistory>();
            ActivityLogs = new Collection<UserActivityLog>();
        }

        /// <summary>
        /// 设置用户名
        /// </summary>
        public void SetUserName(string userName)
        {
            UserName = Check.NotNullOrWhiteSpace(userName, nameof(userName), maxLength: 256);
        }

        /// <summary>
        /// 设置邮箱
        /// </summary>
        public void SetEmail(string email)
        {
            Email = Check.NotNullOrWhiteSpace(email, nameof(email), maxLength: 256);
        }

        /// <summary>
        /// 设置名字
        /// </summary>
        public void SetName(string? name)
        {
            Name = Check.Length(name, nameof(name), maxLength: 64);
            UpdateDisplayName();
        }

        /// <summary>
        /// 设置姓氏
        /// </summary>
        public void SetSurname(string? surname)
        {
            Surname = Check.Length(surname, nameof(surname), maxLength: 64);
            UpdateDisplayName();
        }

        /// <summary>
        /// 更新显示名称
        /// </summary>
        protected virtual void UpdateDisplayName()
        {
            if (!string.IsNullOrWhiteSpace(Name) && !string.IsNullOrWhiteSpace(Surname))
            {
                DisplayName = $"{Name} {Surname}";
            }
            else if (!string.IsNullOrWhiteSpace(Name))
            {
                DisplayName = Name;
            }
            else if (!string.IsNullOrWhiteSpace(Surname))
            {
                DisplayName = Surname;
            }
            else
            {
                DisplayName = UserName;
            }
        }

        /// <summary>
        /// 设置手机号码
        /// </summary>
        public void SetPhoneNumber(string? phoneNumber)
        {
            PhoneNumber = Check.Length(phoneNumber, nameof(phoneNumber), maxLength: 16);
            PhoneNumberConfirmed = false; // 更新手机号需要重新验证
        }

        /// <summary>
        /// 确认手机号码
        /// </summary>
        public void ConfirmPhoneNumber()
        {
            PhoneNumberConfirmed = true;
        }

        /// <summary>
        /// 确认邮箱
        /// </summary>
        public void ConfirmEmail()
        {
            EmailConfirmed = true;
        }

        /// <summary>
        /// 设置密码
        /// </summary>
        public void SetPassword(string passwordHash)
        {
            PasswordHash = Check.NotNullOrWhiteSpace(passwordHash, nameof(passwordHash));
            PasswordChangedAt = Clock.Now;
            SecurityStamp = Guid.NewGuid().ToString();
        }

        /// <summary>
        /// 更新安全码
        /// </summary>
        public void UpdateSecurityStamp()
        {
            SecurityStamp = Guid.NewGuid().ToString();
        }

        /// <summary>
        /// 激活用户
        /// </summary>
        public void Activate()
        {
            if (Status == UserStatus.Active)
            {
                return;
            }

            IsActive = true;
            Status = UserStatus.Active;

            // 添加领域事件
            AddLocalEvent(new UserActivatedEvent(this));
        }

        /// <summary>
        /// 停用用户
        /// </summary>
        public void Deactivate()
        {
            if (Status == UserStatus.Disabled)
            {
                return;
            }

            IsActive = false;
            Status = UserStatus.Disabled;

            // 添加领域事件
            AddLocalEvent(new UserDeactivatedEvent(this));
        }

        /// <summary>
        /// 锁定用户
        /// </summary>
        public void LockOut(DateTime? lockoutEnd)
        {
            LockoutEnd = lockoutEnd;
        }

        /// <summary>
        /// 解锁用户
        /// </summary>
        public void Unlock()
        {
            LockoutEnd = null;
            AccessFailedCount = 0;
        }

        /// <summary>
        /// 增加登录失败次数
        /// </summary>
        public void IncrementAccessFailedCount()
        {
            AccessFailedCount++;
        }

        /// <summary>
        /// 重置登录失败次数
        /// </summary>
        public void ResetAccessFailedCount()
        {
            AccessFailedCount = 0;
        }

        /// <summary>
        /// 更新最后登录信息
        /// </summary>
        public void UpdateLastLoginInfo(DateTime loginTime, string? loginIp = null)
        {
            LastLoginTime = loginTime;
            LastLoginIp = loginIp;
            ResetAccessFailedCount();

            // 添加登录历史记录
            LoginHistories.Add(new UserLoginHistory(
                GuidGenerator.Create(),
                Id,
                loginTime,
                loginIp
            ));
        }

        /// <summary>
        /// 更新头像URL
        /// </summary>
        public void SetAvatarUrl(string? avatarUrl)
        {
            AvatarUrl = Check.Length(avatarUrl, nameof(avatarUrl), maxLength: 512);
        }

        /// <summary>
        /// 更新个人简介
        /// </summary>
        public void SetBio(string? bio)
        {
            Bio = Check.Length(bio, nameof(bio), maxLength: 1000);
        }

        /// <summary>
        /// 添加用户角色
        /// </summary>
        public void AddRole(Guid roleId)
        {
            if (UserRoles.Any(r => r.RoleId == roleId))
            {
                return;
            }

            UserRoles.Add(new UserRole(GuidGenerator.Create(), Id, roleId));
        }

        /// <summary>
        /// 移除用户角色
        /// </summary>
        public void RemoveRole(Guid roleId)
        {
            var userRole = UserRoles.FirstOrDefault(r => r.RoleId == roleId);
            if (userRole != null)
            {
                UserRoles.Remove(userRole);
            }
        }

        /// <summary>
        /// 添加到组织
        /// </summary>
        public void AddToOrganization(Guid organizationId)
        {
            if (OrganizationUnits.Any(ou => ou.OrganizationId == organizationId))
            {
                return;
            }

            OrganizationUnits.Add(new UserOrganizationUnit(
                GuidGenerator.Create(),
                Id,
                organizationId
            ));
        }

        /// <summary>
        /// 从组织中移除
        /// </summary>
        public void RemoveFromOrganization(Guid organizationId)
        {
            var userOrg = OrganizationUnits.FirstOrDefault(ou => ou.OrganizationId == organizationId);
            if (userOrg != null)
            {
                OrganizationUnits.Remove(userOrg);
            }
        }

        /// <summary>
        /// 检查用户是否在指定角色中
        /// </summary>
        public bool IsInRole(Guid roleId)
        {
            return UserRoles.Any(r => r.RoleId == roleId);
        }

        /// <summary>
        /// 检查用户是否在指定组织中
        /// </summary>
        public bool IsInOrganization(Guid organizationId)
        {
            return OrganizationUnits.Any(ou => ou.OrganizationId == organizationId);
        }
    }

    /// <summary>
    /// 用户状态枚举
    /// </summary>
    public enum UserStatus
    {
        /// <summary>
        /// 待激活
        /// </summary>
        Pending = 0,

        /// <summary>
        /// 正常
        /// </summary>
        Active = 1,

        /// <summary>
        /// 禁用
        /// </summary>
        Disabled = 2,

        /// <summary>
        /// 已删除
        /// </summary>
        Deleted = 3
    }
}